import {request} from "@@/exports";
import {ResponseStructure} from "@/requestErrorConfig";
import {ParamsType} from "@ant-design/pro-components";
import {DynamicObject} from "@/services/typings";

export const emptyList = {
  data: [],
  success: true,
  total: 0
}

// 通用请求函数
async function baseRequest<T>(
  method: string,
  url: string,
  data?: any,
  params?: ParamsType,
  options?: DynamicObject
): Promise<ResponseStructure & { data?: T }> {
  try {
    const result = await request<ResponseStructure & { data?: T }>(`/api${url}`, {
      method,
      data,
      params,
      ...(options || {}),
    });
    return result;
  } catch (e: any) {
    console.error(`Request error: ${e.message}`);
    return {
      success: false,
      message: e.message,
    } as any;
  }
}

// 获取数据
export async function get<T>(url: string, params?: ParamsType, data?: DynamicObject, options?: DynamicObject) {
  return baseRequest<T>("GET", url, data, params, options);
}

// 发送 POST 请求
export async function post<T>(url: string, data?: DynamicObject, params?: ParamsType, options?: DynamicObject) {
  return baseRequest<T>("POST", url, data, params, options);
}

// 发送 PUT 请求
export async function put<T>(url: string, data?: DynamicObject, params?: ParamsType, options?: DynamicObject) {
  return baseRequest<T>("PUT", url, data, params, options);
}

// 发送 DELETE 请求
export async function del<T>(url: string, data?: DynamicObject, params?: ParamsType, options?: DynamicObject) {
  return baseRequest<T>("DELETE", url, data, params, options);
}

// 分页数据
export async function pageData<T>(url: string, params?: ParamsType, options?: DynamicObject) {
  return baseRequest<T>("GET", `${url}/page`, undefined, params, options);
}

// 列表数据
export async function listData<T>(url: string, params?: ParamsType, options?: DynamicObject) {
  return baseRequest<T>("GET", `${url}/list`, undefined, params, options);
}

// 根据 ID 更新
export async function updateById<T>(url: string, data: T, options?: DynamicObject) {
  return baseRequest<T>("PUT", `${url}/updateById`, data, undefined, options);
}

// 更新数据
export async function update<T>(url: string, data: T, options?: DynamicObject) {
  return baseRequest<T>("PUT", url, data, undefined, options);
}

// 新增数据
export async function addData<T>(url: string, data: T, options?: DynamicObject) {
  return baseRequest<T>("POST", url, data, undefined, options);
}

// 根据 ID 删除
export async function deleteById(url: string, id: string | number, options?: DynamicObject) {
  return baseRequest("DELETE", `${url}/${id}`, undefined, undefined, options);
}

// 删除数据
export async function deleteData(url: string, data: any, params?: DynamicObject, options?: DynamicObject) {
  return baseRequest("DELETE", url, data, params, options);
}

// 根据 ID 获取数据
export async function getById<T>(url: string, id: string | number, options?: DynamicObject) {
  return baseRequest<T>("GET", `${url}/${id}`, undefined, undefined, options);
}
